<template>
  <view class="padding-sm">
    <view class="search-area">
      <view class="search-input cu-bar bg-white search solid-bottom">
        <view class="search-form round">
          <text class="cuIcon-search"></text>
          <input type="text" placeholder="输入医生姓名查询医生" confirm-type="search" v-model="paramObj.realName"></input>
        </view>
        <view class="action">
          <button class="cu-btn bg-cyan round" @click="search">搜索</button>
        </view>
      </view>
      <!-- 索引条 -->
      <ill-sub @clickSub="changeSub" ref="mySub"></ill-sub>
    </view>

    <view class="cu-bar bg-white solid-bottom margin-top-sm">
      <view class="action">
        <text class="cuIcon-title text-cyan"></text>
        <text class="text-xl text-bold">选择医生</text>
      </view>
    </view>

    <scroll-view scroll-y class="indexes" :style="[{height: 'calc(100vh - 50px)'}]" :scroll-with-animation="true">
      <view class="cu-list menu-avatar no-padding">
        <view class="cu-item" v-for="(item,index) in dataList" :key="index" @click="goChat(item)">
          <!-- 头像 -->
          <view class="cu-avatar round lg" :style="{'background-image': 'url(' + item.avatar + ')'}" v-if="item.avatar">
          </view>
          <view class="cu-avatar round lg" v-else>{{ item.firstName }}</view>
          <!-- 名字 -->
          <view class="content">
            <view class="text-grey">{{item.realName}}</view>
            <!-- 名字下的描述 -->
            <view class="text-gray text-sm" v-if="item.noneVisitCount > 0">
              有<uni-badge class="uni-badge-left-margin" :text="item.noneVisitCount" type="warning" />条新消息
            </view>
            <view class="text-gray text-sm" v-else>
              暂无消息
            </view>
          </view>
        </view>
      </view>
    </scroll-view>

  </view>
</template>

<script>
  import {
    mapMutations
  } from 'vuex'

  export default {
    data() {
      return {
        firstLoad: true,
        paramObj: {
          realName: null,
          deptId: null,
          pageNum: 1,
          pageSize: 10
        },
        total: 0,
        isLoading: false,
        dataList: [],
      };
    },
    beforeDestroy() {
      this.dataList = []
    },
    onShow() {
      this.init();
    },
    methods: {
      ...mapMutations('m_user', ['redirectLoginAsync']),
      // 初始化
      async init() {
        // 如果存在Tab页组件
        const tabPath = '/' + this.getCurrentTabPath();
        await this.redirectLoginAsync(tabPath);
        if (!this.firstLoad) {
          this.resetData();
          this.loadMoreData();
        }
      },
      // 获取当前页面路径
      getCurrentTabPath() {
        const pages = getCurrentPages(); // 获取当前页面栈
        return pages[pages.length - 1].route;
      },
      // 下拉重载方法
      onPullDownRefresh() {
        // 重新加载数据
        this.resetData();
        this.loadMoreData();
      },
      // 跳转到顶部
      scrollToTop() {
        this.$nextTick(() => {
          uni.pageScrollTo({
            scrollTop: 0, // 设置一个很大的值，确保滚动到底部
            duration: 100, // 滚动动画的时长
          });
        })
      },
      // 跳转到底部
      scrollToBottom() {
        this.$nextTick(() => {
          uni.pageScrollTo({
            scrollTop: 9999, // 设置一个很大的值，确保滚动到底部
            duration: 300, // 滚动动画的时长
          });
        })
      },
      // 滚动到底部
      onReachBottom() {
        // 当滚动到底部时触发上拉加载更多
        this.loadMoreData();
      },
      // 加载更多数据
      loadMoreData() {
        // 如果已经没有更多数据或正在加载中，则不再进行加载
        if (this.paramObj.pageNum !== 1 && this.dataList.length >= this.total) {
          uni.$showMsg('数据已加载完毕!');
          return;
        } else if (this.isLoading) {
          uni.$showMsg('正在玩命加载中!');
          return;
        }
        this.getChatUsers();
      },
      // 重新赋值
      resetData() {
        this.dataList = [];
        this.total = 0;
        this.paramObj.pageNum = 1;
      },
      // 切换病情
      changeSub(subId) {
        this.paramObj.deptId = subId;
        this.resetData();
        this.loadMoreData();
        this.scrollToTop();
      },
      // 跳转到聊天界面
      goChat(item) {
        uni.navigateTo({
          url: `/subpkg/chat_detail/chat_detail?name=${item.realName}&id=${item.userId}&avatar=${item.avatar}`
        })
      },
      // 获取到聊天用户集合
      async getChatUsers() {
        // 判断subId
        if (!this.paramObj.deptId) {
          return;
        }
        this.isLoading = true; // 标记为正在加载中
        let requeryParams = null;
        if (!this.paramObj.realName) {
          requeryParams = {
            pageNum: this.paramObj.pageNum,
            pageSize: this.paramObj.pageSize,
            deptId: this.paramObj.deptId
          };
        } else {
          requeryParams = this.paramObj;
        }
        // 发起请求
        const {
          data: res
        } = await uni.$http.get('/chat/doctors', requeryParams)
        // 判断是否获取失败
        if (res.code !== 200) return uni.$showMsg();
        if (this.paramObj.pageNum === 1) {
          // 下拉重载，清空原有数据
          this.dataList = res.data.list;
        } else {
          // 上拉加载，追加数据
          this.dataList = [...this.dataList, ...res.data.list];
          this.scrollToBottom();
        }
        this.total = res.data.totalCount;
        this.paramObj.pageNum++;
        this.isLoading = false; // 标记为加载完成
        if (this.firstLoad) {
          // 解除第一次加载
          this.firstLoad = false;
        }
      },
      // 搜索请求
      async search() {
        // 发起请求
        this.resetData();
        this.loadMoreData();
      }
    }
  }
</script>

<style lang="scss">
  .search-area {
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    height: 110px;
    border-radius: 5px;
    background: #fff;
    padding-top: 5px;
    position: sticky;
    top: 0;
    z-index: 999;
  }

  .indexes {
    position: relative;
    margin-top: 0px;
  }
</style>